import * as session from 'koa-session';
import * as logger from 'koa-logger';
import * as helmet from "koa-helmet";
import * as server from 'koa-static';
import * as koaBody from 'koa-body';
import * as cors from 'koa2-cors';

import utils from '../utils';

const env = process.env.NODE_ENV === 'production' ? false : true;

export const addBody = (app:any) => {

  app.use(
    koaBody({
      // multipart:true, // 支持文件上传
      // // encoding:'gzip',
      // formidable:{
      //   uploadDir:path.join(__dirname,'../../public/upload/'), // 设置文件上传目录
      //   keepExtensions: true,    // 保持文件的后缀
      //   maxFieldsSize:2 * 1024 * 1024, // 文件上传大小
      //   onFileBegin:(name,file) => { // 文件上传前的设置
      //     // 获取文件后缀
      //     const ext = getUploadFileExt(file.name);
      //     // 最终要保存到的文件夹目录
      //     const dirName = getUploadDirName();
      //     const dir = path.join(__dirname, `../../public/upload/${dirName}`);
      //     // 检查文件夹是否存在如果不存在则新建文件夹
      //     checkDirExist(dir);
      //     // 获取文件名称
      //     const fileName = getUploadFileName(ext);
      //     // 重新覆盖 file.path 属性
      //     file.path = `${dir}/${fileName}`;
      //     app.context.uploadpath = app.context.uploadpath ? app.context.uploadpath : {};
      //     app.context.uploadpath[name] = `${dirName}/${fileName}`;
      //   },
      //   onError:(err)=>{
      //     console.log(err);
      //   }
      // }
    })
  );

  // app.use(function(ctx, next){
  //   return next().catch((err) => {
  //     if (401 == err.status) {
  //       ctx.status = 401;
  //       ctx.body = {
  //         code: 404,
  //         msg: '对不起，您没有权限访问，请先登录\n'
  //       }
  //     } else {
  //       throw err;
  //     }
  //   });
  // });

  // app.use(setKoaJwt())
}

export const addSession = (app:any) => {
  app.keys = ['got']

  const CONFIG = {
    key: 'koa:sess',
    maxAge: 28800000,
    overwrite: true,
    httpOnly: true,
    signed: true,
    rolling: true,
    renew: false,
  }

  app.use(session(CONFIG, app))
}

export const addCors = (app:any) => {
  app.use(
    cors({
      origin: function (ctx) {
        // if (ctx.url === '/test') {
        //    return "*"; // 允许来自所有域名请求
        // }
        return 'http://localhost:8088'; // 这样就能只允许 http://localhost:8080 这个域名的请求了
      },
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
      maxAge: 5,
      credentials: true,
      allowMethods: ['GET', 'POST', 'DELETE'],
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    })
  )
}

export const addMsg = (app:any) => {
  app.use(async (ctx:any, next:Function) => {
    ctx.sendMsg = (key:string, ...args:Array<any>) => {
      ctx.body = utils.message(key, ...args)
    }
    await next()
  })
}

export const addServer = (app:any) => {app.use(server('public'))}

export const addHelmet = (app:any) => {app.use(helmet())}

export const addLogger = (app:any) => {
  if (env) {
    app.use(logger())
  }
}
